import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

// 会员中心：会员基本信息、等级、积分、储值
export const useMemberStore = defineStore('member', () => {
  const STORAGE_KEY = 'erppos_members'
  const HISTORY_KEY = 'erppos_member_recharge'
  const members = ref([])
  const rechargeHistory = ref([])

  // 示例等级规则（可替换为服务端）
  const tierRules = ref([
    { key: 'normal', name: '普通', minPoints: 0 },
    { key: 'silver', name: '银卡', minPoints: 1000 },
    { key: 'gold', name: '金卡', minPoints: 3000 },
    { key: 'platinum', name: '铂金', minPoints: 8000 },
  ])

  const initializeMembers = () => {
    const cached = localStorage.getItem(STORAGE_KEY)
    const cachedHistory = localStorage.getItem(HISTORY_KEY)
    if (cached) members.value = JSON.parse(cached)
    if (cachedHistory) rechargeHistory.value = JSON.parse(cachedHistory)
    if (cached) return
    members.value = [
      { id: 'M001', name: '王芳', phone: '13800000001', gender: 'F', birthday: '1995-06-01', tier: 'silver', points: 1680, balance: 120, createdAt: '2024-01-02', lastVisit: '2024-05-01' },
      { id: 'M002', name: '李强', phone: '13900000002', gender: 'M', birthday: '1990-03-18', tier: 'gold', points: 3680, balance: 560, createdAt: '2024-02-10', lastVisit: '2024-05-03' },
      { id: 'M003', name: '赵敏', phone: '13700000003', gender: 'F', birthday: '1998-11-22', tier: 'normal', points: 200, balance: 0, createdAt: '2024-03-05', lastVisit: '2024-04-28' },
    ]
  }

  const totalMembers = computed(() => members.value.length)
  const totalBalance = computed(() => members.value.reduce((s, m) => s + Number(m.balance || 0), 0))
  const totalPoints = computed(() => members.value.reduce((s, m) => s + Number(m.points || 0), 0))

  const getFilteredMembers = (filters) => {
    return members.value.filter(m => {
      if (filters.search) {
        const s = filters.search.toLowerCase()
        if (!m.name.toLowerCase().includes(s) && !m.phone.includes(filters.search)) return false
      }
      if (filters.tier && m.tier !== filters.tier) return false
      return true
    })
  }

  const persist = () => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(members.value))
    localStorage.setItem(HISTORY_KEY, JSON.stringify(rechargeHistory.value))
  }

  const addMember = (data) => {
    const id = 'M' + Date.now()
    const now = new Date().toISOString().slice(0, 10)
    const item = {
      id,
      name: data.name,
      phone: data.phone,
      gender: data.gender || 'U',
      birthday: data.birthday || '',
      tier: data.tier || 'normal',
      points: Number(data.points || 0),
      balance: Number(data.balance || 0),
      createdAt: now,
      lastVisit: now,
    }
    members.value.unshift(item)
    persist()
    return item
  }

  const updateMember = (id, updates) => {
    const idx = members.value.findIndex(m => m.id === id)
    if (idx === -1) return null
    members.value[idx] = {
      ...members.value[idx],
      ...updates,
    }
    persist()
    return members.value[idx]
  }

  const deleteMember = (id) => {
    const idx = members.value.findIndex(m => m.id === id)
    if (idx === -1) return false
    members.value.splice(idx, 1)
    persist()
    return true
  }

  const rechargeBalance = (id, amount) => {
    const m = members.value.find(x => x.id === id)
    if (!m) return null
    m.balance = Number((Number(m.balance || 0) + Number(amount || 0)).toFixed(2))
    // 记录充值流水
    rechargeHistory.value.unshift({
      id: 'RC' + Date.now(),
      memberId: m.id,
      name: m.name,
      phone: m.phone,
      amount: Number(amount || 0),
      date: new Date().toISOString(),
      operator: '系统',
    })
    persist()
    return m.balance
  }

  const adjustPoints = (id, delta) => {
    const m = members.value.find(x => x.id === id)
    if (!m) return null
    m.points = Math.max(0, Number(m.points || 0) + Number(delta || 0))
    // 根据积分变更自动调整等级
    const sorted = [...tierRules.value].sort((a, b) => b.minPoints - a.minPoints)
    m.tier = (sorted.find(t => m.points >= t.minPoints) || sorted[sorted.length - 1]).key
    persist()
    return m.points
  }

  return {
    members,
    tierRules,
    rechargeHistory,
    totalMembers,
    totalBalance,
    totalPoints,
    initializeMembers,
    getFilteredMembers,
    addMember,
    updateMember,
    deleteMember,
    rechargeBalance,
    adjustPoints,
  }
})


